{% extends "base.html" %}

{% block title %}JSON格式化工具 - 开发者工具{% endblock %}

{% block content %}
<div class="container py-4">
    <div class="row mb-4">
        <div class="col-12">
            <h1 class="h3 mb-2">JSON格式化工具</h1>
            <p class="text-muted">格式化、压缩、验证JSON数据，支持语法高亮</p>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm mb-4">
                <div class="card-body">
                    <div class="mb-3">
                        <textarea id="jsonInput" class="form-control" rows="10" placeholder='在此粘贴您的JSON数据，例如：{"name": "张三", "age": 25, "skills": ["HTML", "CSS", "JavaScript"]}'></textarea>
                    </div>
                    <div class="mb-4">
                        <div class="d-flex flex-wrap gap-2">
                            <button id="formatBtn" class="btn btn-primary">
                                <i class="fas fa-indent me-1"></i> 格式化
                            </button>
                            <button id="minifyBtn" class="btn btn-secondary">
                                <i class="fas fa-compress-alt me-1"></i> 压缩
                            </button>
                            <button id="validateBtn" class="btn btn-info">
                                <i class="fas fa-check-circle me-1"></i> 验证
                            </button>
                            <button id="originalBtn" class="btn btn-outline-secondary">
                                <i class="fas fa-undo me-1"></i> 恢复原始
                            </button>
                            <button id="copyBtn" class="btn btn-success">
                                <i class="fas fa-copy me-1"></i> 复制
                            </button>
                            <button id="clearBtn" class="btn btn-danger">
                                <i class="fas fa-trash-alt me-1"></i> 清空
                            </button>
                        </div>
                    </div>
                    <div id="resultStats" class="small text-muted mb-3" style="display: none;">
                        <div class="row">
                            <div class="col-md-4">
                                <span><i class="fas fa-file-alt me-1"></i> 字符数: <span id="charCount">0</span></span>
                            </div>
                            <div class="col-md-4">
                                <span><i class="fas fa-outdent me-1"></i> 行数: <span id="lineCount">0</span></span>
                            </div>
                            <div class="col-md-4">
                                <span><i class="fas fa-weight-hanging me-1"></i> 大小: <span id="byteSize">0</span> bytes</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="card shadow-sm">
                <div class="card-body">
                    <h5 class="card-title mb-3">格式化结果</h5>
                    <pre id="jsonResult" class="bg-light p-3 rounded" style="min-height: 200px;"><!-- 格式化后的JSON将在这里显示 --></pre>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const jsonInput = document.getElementById('jsonInput');
        const jsonResult = document.getElementById('jsonResult');
        const formatBtn = document.getElementById('formatBtn');
        const minifyBtn = document.getElementById('minifyBtn');
        const validateBtn = document.getElementById('validateBtn');
        const originalBtn = document.getElementById('originalBtn');
        const copyBtn = document.getElementById('copyBtn');
        const clearBtn = document.getElementById('clearBtn');
        const resultStats = document.getElementById('resultStats');
        const charCount = document.getElementById('charCount');
        const lineCount = document.getElementById('lineCount');
        const byteSize = document.getElementById('byteSize');

        let originalJson = '';

        // 格式化JSON
        formatBtn.addEventListener('click', function() {
            const jsonData = jsonInput.value.trim();
            if (!jsonData) {
                showAlert('请先输入JSON数据', 'warning');
                return;
            }

            saveOriginal();
            sendJsonRequest('format', jsonData);
        });

        // 压缩JSON
        minifyBtn.addEventListener('click', function() {
            const jsonData = jsonInput.value.trim();
            if (!jsonData) {
                showAlert('请先输入JSON数据', 'warning');
                return;
            }

            saveOriginal();
            sendJsonRequest('minify', jsonData);
        });

        // 验证JSON
        validateBtn.addEventListener('click', function() {
            const jsonData = jsonInput.value.trim();
            if (!jsonData) {
                showAlert('请先输入JSON数据', 'warning');
                return;
            }

            sendJsonRequest('validate', jsonData);
        });

        // 恢复原始JSON
        originalBtn.addEventListener('click', function() {
            if (originalJson) {
                jsonInput.value = originalJson;
                jsonResult.textContent = '已恢复为原始JSON';
                updateStats(originalJson);
            } else {
                showAlert('没有保存的原始JSON', 'info');
            }
        });

        // 复制结果
        copyBtn.addEventListener('click', function() {
            const text = jsonResult.textContent;
            if (!text || text === '<!-- 格式化后的JSON将在这里显示 -->') {
                showAlert('没有可复制的内容', 'warning');
                return;
            }

            navigator.clipboard.writeText(text).then(function() {
                showAlert('已复制到剪贴板', 'success');
            }).catch(function(err) {
                showAlert('复制失败: ' + err, 'danger');
            });
        });

        // 清空输入
        clearBtn.addEventListener('click', function() {
            jsonInput.value = '';
            jsonResult.textContent = '<!-- 格式化后的JSON将在这里显示 -->';
            resultStats.style.display = 'none';
            originalJson = '';
        });

        // 保存原始JSON
        function saveOriginal() {
            if (jsonInput.value.trim() && jsonInput.value !== originalJson) {
                originalJson = jsonInput.value;
            }
        }

        // 发送JSON请求
        function sendJsonRequest(action, jsonData) {
            fetch('/dev-tools/json-formatter', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: action,
                    json_data: jsonData
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.error === 0) {
                    if (action === 'validate') {
                        if (data.body.valid) {
                            showAlert('JSON格式有效!', 'success');
                        } else {
                            showAlert('JSON格式无效: ' + data.body.message, 'danger');
                        }
                    } else {
                        jsonResult.textContent = data.body.result;
                        jsonInput.value = data.body.result;
                        updateStats(data.body.result);
                    }
                } else {
                    showAlert(data.message || '处理JSON时出错', 'danger');
                }
            })
            .catch(error => {
                showAlert('请求失败: ' + error, 'danger');
            });
        }

        // 更新统计信息
        function updateStats(text) {
            if (text) {
                resultStats.style.display = 'block';
                charCount.textContent = text.length;
                lineCount.textContent = (text.match(/\n/g) || []).length + 1;
                byteSize.textContent = new Blob([text]).size;
            } else {
                resultStats.style.display = 'none';
            }
        }

        // 显示提示
        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed bottom-0 end-0 m-3`;
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            `;
            document.body.appendChild(alertDiv);
            
            // 3秒后自动关闭
            setTimeout(() => {
                const bsAlert = new bootstrap.Alert(alertDiv);
                bsAlert.close();
            }, 3000);
        }
    });
</script>
{% endblock %} 